package cn.muqingfeng.bbs.ui;

import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import cn.muqingfeng.api.RequestHelper;
import cn.muqingfeng.api.UriHelper;
import cn.muqingfeng.api.request.GsonRequest;
import cn.muqingfeng.api.to.ArticleDetailFloorsInfoTO;
import cn.muqingfeng.api.to.ArticleDetailThreadTO;
import cn.muqingfeng.api.to.ArticleTO;
import cn.muqingfeng.api.to.BaseArticleDetailTO;
import cn.muqingfeng.api.to.ReplyTO;
import cn.muqingfeng.api.to.UserTO;
import cn.muqingfeng.bbs.R;
import cn.muqingfeng.bbs.adapter.ArticleDetailAdapter;
import cn.muqingfeng.bbs.constants.Constants;
import cn.muqingfeng.bbs.ui.widget.xlistview.XListView;
import cn.muqingfeng.bbs.ui.widget.xlistview.XListView.IXListViewListener;
import cn.muqingfeng.util.AccountManager;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;

public class ArticleDetailActivity extends BaseActivity implements OnClickListener {
	private static final int REQUEST_CODE_MAIN = 505;
	private static final Object LOCK = new Object();
	private ArticleTO mArticle;
	private ProgressBar mProgressBar;
	private XListView mListLayout;
	private ArticleDetailAdapter mAdapter;
	private boolean isLoading = false;
	private int mCurrentPage = 1;
	private String mFid;
	private ViewGroup mCommentLayout;
	private Button mSendButton;
	private EditText mCommentView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.article_detail);
		mArticle = getIntent().getParcelableExtra(Constants.EXTRA_ARTICLE);
		mFid = getIntent().getStringExtra(Constants.EXTRA_FID);
		setupViews();
	}

	private void setupViews() {
		// mArticle.setId("423964");
		findViewById(R.id.back).setOnClickListener(this);
		mSendButton = (Button) findViewById(R.id.send);
		mSendButton.setOnClickListener(this);
		mCommentView = (EditText) findViewById(R.id.comment);
		View sendView = findViewById(R.id.to_send);
		sendView.setOnClickListener(this);
		mCommentLayout = (ViewGroup) findViewById(R.id.comment_layout);
		if (TextUtils.isEmpty(mFid)) {
			mCommentLayout.setVisibility(View.GONE);
		}
//		sendView.setVisibility(View.GONE);
		mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
		mListLayout = (XListView) findViewById(R.id.list_layout);
		mListLayout.setDivider(getResources().getDrawable(R.drawable.divider));
		mListLayout.setFooterDividersEnabled(false);
		mListLayout.setPullRefreshEnable(false);
		mListLayout.setPullLoadEnable(true, getString(R.string.xlistview_footer_hint_normal));
		mListLayout.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
			}

			@Override
			public void onLoadMore() {
				loadFromNetwork(mCurrentPage + 1);
			}
		});
		mAdapter = new ArticleDetailAdapter(this, mArticle.getId());
		mListLayout.setAdapter(mAdapter);
		loadFromNetwork(1);
	}

	private void loadFromNetwork(final int page) {
		synchronized (LOCK) {
			if (isLoading)
				return;
			isLoading = true;
			String url = UriHelper.getArticleDetailUrl();
			HashMap<String, String> params = new HashMap<String, String>();
			params.put(UriHelper.PARAMS_TID, mArticle.getId());
			final int pageSize = 100;// Constants.DEFAULT_PAGE_SIZE;
			params.put(UriHelper.PARAMS_PAGE_SIZE_1, String.valueOf(pageSize));
			params.put(UriHelper.PARAMS_PAGE_NO, String.valueOf(page));
			GsonRequest<BaseArticleDetailTO> request = new GsonRequest<BaseArticleDetailTO>(Method.POST, url, new Listener<BaseArticleDetailTO>() {

				@Override
				public void onResponse(BaseArticleDetailTO response) {
					isLoading = false;
					if (!isDestroied()) {
						mCurrentPage = page;
						ArticleDetailThreadTO thread = response.getThread();
						List<ArticleDetailFloorsInfoTO> postlist = response.getPostList();
						int count = postlist == null ? 0 : postlist.size();
						mListLayout.stopLoadMore();
						if (pageSize >= count) {
							mListLayout.setPullLoadEnable(false, null);
						}
						mAdapter.setArticleDetail(thread, postlist);
						mProgressBar.setVisibility(View.GONE);
						mListLayout.setVisibility(View.VISIBLE);
						mAdapter.notifyDataSetChanged();
					}
				}
			}, new ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError error) {
					isLoading = false;
					if (mCurrentPage > 0) {
						mCurrentPage--;
					}
					if (!isDestroied()) {
						Toast.makeText(getApplicationContext(), "加载失败，请重试", Toast.LENGTH_SHORT).show();
						mProgressBar.setVisibility(View.GONE);
						mListLayout.setVisibility(View.VISIBLE);
					}
				}
			}, params, BaseArticleDetailTO.class);
			RequestHelper.startRequest(getApplicationContext(), request);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		mAdapter.setUserTO(AccountManager.getUser(getApplicationContext()));
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
			finish();
			break;
		case R.id.send: {
			UserTO userTo = AccountManager.getUser(getApplicationContext());
			if (userTo == null) {
				showNOLoginDialog();
			} else {
				sendComment();
			}
			break;
		}
		case R.id.to_send: {
//			Intent intent = new Intent(this, SendArticleActivity.class);
//			intent.putExtra(Constants.EXTRA_FID, mFid);
//			startActivity(intent);
			UserTO userTo = AccountManager.getUser(getApplicationContext());
			if (userTo == null) {
				showNOLoginDialog();
			} else {
				startActivity(new Intent(this, SendArticleActivity.class));
			}
		}
			break;
		default:
			break;
		}
	}

	private void sendComment() {
		String text = mCommentView.getText().toString();
		if (TextUtils.isEmpty(text.trim())) {
			Toast.makeText(getApplicationContext(), "请输入评论内容", Toast.LENGTH_SHORT).show();
			return;
		}
		mSendButton.setClickable(false);
		Toast.makeText(getApplicationContext(), "评论发送中...", Toast.LENGTH_SHORT).show();
		String url = UriHelper.getReplyArticleUrl();
		HashMap<String, String> params = new HashMap<String, String>();
		params.put(UriHelper.PARAMS_FID, mFid);
		params.put(UriHelper.PARAMS_TID, mArticle.getId());
		params.put(UriHelper.PARAMS_MESSAGE, text);
		GsonRequest<ReplyTO> request = new GsonRequest<ReplyTO>(Method.POST, url, new Listener<ReplyTO>() {

			@Override
			public void onResponse(ReplyTO response) {
				if (!isDestroied()) {
					mSendButton.setClickable(true);
					if (response != null && response.isSuccess()) {
						mCommentView.setText("");
						Toast.makeText(getApplicationContext(), "评论成功！评论需要审核，请等待通过", Toast.LENGTH_SHORT).show();
					}else{
						Toast.makeText(getApplicationContext(), "评论失败，请重试！", Toast.LENGTH_SHORT).show();
					}
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				if (!isDestroied()) {
					mSendButton.setClickable(true);
					Toast.makeText(getApplicationContext(), "评论失败，请重试！", Toast.LENGTH_SHORT).show();
				}
			}
		}, params, ReplyTO.class);
		request.setNeedLogin(true);
		RequestHelper.startRequest(getApplicationContext(), request);
	}
	
	private AlertDialog mNoLoginDialog;
	
	private synchronized void showNOLoginDialog() {
		if (mNoLoginDialog != null && mNoLoginDialog.isShowing()) {
			return;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("提示");
		builder.setMessage("您还未登录，是否立即登录？");
		builder.setNegativeButton("否", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});
		builder.setPositiveButton("是", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent(ArticleDetailActivity.this, LoginActivity.class);
				intent.putExtra(Constants.EXTRA_ACTION, LoginActivity.ACTION_RETURN);
				startActivityForResult(intent, REQUEST_CODE_MAIN);
			}
		});
		mNoLoginDialog = builder.create();
		mNoLoginDialog.show();
	}
}
